﻿using CoreEx.Common.Cache;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;

namespace CoreEx.Common.Logging
{
    /// <summary>
    /// Provides a base class for implementing <see cref="ILogger"/> factories.    
    /// </summary>    
    /// <remarks>
    /// 
    /// </remarks>
    public abstract class LoggerFactoryBase : ILoggerFactory, IInitialize
    {
        private ILazyCache<string, ILogger> _cache;        
        private IServiceContainer _serviceContainer;


        /// <summary>
        /// Returns an <see cref="ILogger"/> instance
        /// </summary>
        /// <param name="name">The name of the <see cref="ILogger"/> to return.</param>
        /// <returns><see cref="ILogger"/></returns>
        public ILogger GetLogger(string name)
        {
            var loggerName = GetLoggerName(name);
            var logger = _cache.GetValue(loggerName, CreateLogger);
            return logger;
        }


        /// <summary>
        /// Creates a <see cref="ILogger"/> instance
        /// </summary>
        /// <param name="name">The name of the logger</param>
        /// <returns><see cref="ILogger"/></returns>
        protected abstract ILogger CreateLogger(string name);



        private static string GetLoggerName(string name)
        {
            return string.IsNullOrEmpty(name) ? "DefaultLog" : name;
        }

        /// <summary>
        /// Initializes this service instance.
        /// </summary>
        /// <param name="source"></param>
        public virtual void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
            _cache = _serviceContainer.GetService<ILazyCache<string, ILogger>>();
        }
    }
}
